const log = console.log,
      err = console.error,
      exit = process.exit,
      fs = require('fs'),
      join = require('path').join,
      instruction = process.argv[2],
      fileName = process.argv[3]; 

const demandDir = join(__dirname, 'sysFile'),
      dir = fs.readdirSync(demandDir);

let fileMessage = [],
    birthtimeMs = [];

if(instruction === '-list') {
  for(let i=0; i<dir.length; i++) {
    
    let src = join(demandDir, dir[i]);
    
    birthtimeMs[i] = fs.statSync(src).birthtimeMs;
    
    const createTime = new Date(birthtimeMs[i]);
    
    let year = createTime.getFullYear(),
        month = createTime.getMonth() + 1,
        date = createTime.getDate(),
        hour = createTime.getHours(),
        minute = createTime.getMinutes();
    hour = hour<10?'0'+hour:hour;
    minute = minute<10?'0'+minute:minute;

    let time = year + '-' + month + '-' + date + ' ' + hour + ':' + minute;  
    
    let fileObj = {
      filename: dir[i],
      fileSize: fs.statSync(src).size,
      createTime: time
    }
    fileMessage[i] = fileObj;
  }

  for(let i=0; i<fileMessage.length-1; i++) {
    for(let j=0; j<fileMessage.length-i-1; j++) {
      if(birthtimeMs[j] > birthtimeMs[j+1]) {
        
        let tempBirthtimeMs = birthtimeMs[j];
        birthtimeMs[j] = birthtimeMs[j+1];
        birthtimeMs[j+1] = tempBirthtimeMs;
        
        let temp = fileMessage[j];
        fileMessage[j] = fileMessage[j+1];
        fileMessage[j+1] = temp;
      }
    }
  } 

  fileMessage = JSON.stringify(fileMessage);
  console.log(fileMessage);
}

if(instruction === '-show') {
  const catFileName = join(__dirname, 'sysFile', fileName);
  
  try {

    if(!fs.existsSync(catFileName)) {
      err('%s not exist!', fileName);
      exit(1);
    }

    log(fs.readFileSync(catFileName).toString('utf8'));
  
  } catch(e) {
    err(e.message);
  }
}

function deleteDir(folder) {
  let files = fs.readdirSync(folder);

  for(let i=0; i<files.length; i++) {
    let file = join(folder, files[i]);

    if(fs.statSync(file).isFile()) {
      fs.unlinkSync(file);
      continue;
    }

    if(fs.statSync(file).isDirectory()) deleteDir(file);
  }

  fs.rmdirSync(folder);
}

if(instruction === '-del') {
  const delFileName = join(demandDir, fileName);

  try{

    if(!fs.existsSync(delFileName)) {
      err('%s not exist!', fileName);
      exit(2);
    }

    if(fs.statSync(delFileName).isFile()) fs.unlinkSync(delFileName);

    if(fs.statSync(delFileName).isDirectory()) deleteDir(delFileName);

    log( '%s删除成功！', fileName);
   
  }
  catch(e){
    err(e.message);
  }
}
